<template>
  <section class="component modify-client">
    <el-form
      :model="modifyModel"
      :rules="rules"
      ref="modify-form"
      label-width="120px"
      class="text-left"
    >
      <div class="modify-client-title">基本信息</div>
      <el-row>
        <el-col :span="12">
          <el-form-item label="委托方名称" prop="name">
            <el-input v-model="modifyModel.name"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="委托方代码" prop="principalCode">
            <el-input v-model="modifyModel.principalCode"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="机构类型" prop="outSourceType">
            <el-select v-model="modifyModel.outSourceType">
              <el-option
                v-for="{ code, name, index } in $dict.getDictData(
                  'OutSourceType'
                )"
                :key="index"
                :label="name"
                :value="code"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="状态" prop="commonState">
            <el-select v-model="modifyModel.commonState">
              <el-option
                v-for="{ code, name, index } in $dict.getDictData(
                  'CommonState'
                )"
                :key="index"
                :label="name"
                :value="code"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="所属区域" prop="areaIds">
        <el-cascader
          v-model="modifyModel.areaIds"
          :options="$city.getCityData()"
          change-on-select
          clearable
          style="width: 505px"
        ></el-cascader>
      </el-form-item>
      <el-form-item label="详细地址" prop="address">
        <el-input v-model="modifyModel.address" style="width: 505px"></el-input>
      </el-form-item>
      <el-row>
        <el-col :span="12">
          <el-form-item label="联系人" prop="contactName">
            <el-input v-model="modifyModel.contactName"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系电话" prop="phone">
            <el-input v-model="modifyModel.phone" :maxlength="11"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="邮箱" prop="mail">
            <el-input v-model="modifyModel.mail"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="催收区域" prop="collectArea">
            <el-input v-model="modifyModel.collectArea"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="委托起始日" prop="startTime">
            <el-date-picker
              type="date"
              :picker-options="$common.datePickDisabledDate(1)"
              v-model="modifyModel.startTime"
              value-format="yyyy-MM-dd 00:00:00"
              placeholder="请选择日期"
            ></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="委托截止日" prop="endTime">
            <el-date-picker
              type="date"
              :picker-options="$common.datePickDisabledDate(1)"
              v-model="modifyModel.endTime"
              value-format="yyyy-MM-dd 23:59:59"
              placeholder="请选择日期"
            ></el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="回款确认方式" prop="paymentConfirmType">
        <el-select v-model="modifyModel.paymentConfirmType">
          <el-option
            v-for="{ code, name, index } in $dict.getDictData(
              'PaymentConfirmType'
            )"
            :key="index"
            :label="name"
            :value="code"
          >
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="备注" prop="contents">
        <el-input
          type="textarea"
          v-model="modifyModel.contents"
          style="width: 505px"
          :maxlength="500"
          show-word-limit
        ></el-input>
      </el-form-item>

      <div class="modify-client-title">
        <span class="float-left">收款账户</span>
        <el-button
          @click="onClickAccount"
          class="float-right"
          style="margin-right:25px"
          >新增收款账户</el-button
        >
      </div>
      <add-account v-model="receivAccountRequest" ref="add-account" />

      <div class="modify-client-title">
        <span class="float-left">佣金设置</span>
        <el-button
          @click="onClickCommision"
          class="float-right"
          style="margin-right:25px"
          >新增佣金设置</el-button
        >
      </div>
      <commission-set
        v-model="commissionDetail"
        :isCommission="true"
        ref="commission-set"
      />
    </el-form>

    <div class="operate-buttons">
      <el-button @click="close">取消</el-button>
      <el-button @click="commit">确定</el-button>
    </div>
  </section>
</template>

<script lang="ts">
import Vue from "vue";
import Component from "vue-class-component";
import { Dependencies } from "~/core/decorator";
import { State, Action, Getter } from "vuex-class";
import { PrincipalService } from "~/services/domain-service/principal.service";
import { Emit } from "vue-property-decorator";
import { Form } from "element-ui";
import AddAccount from "~/components/case-import/client-manage/add-account.vue";
import CommissionSet from "~/components/case-import/client-manage/commission-set.vue";
import { FileUploadService } from "~/services/file-service/file-upload.service";

@Component({
  components: {
    AddAccount,
    CommissionSet
  }
})
export default class ModifyClient extends Vue {
  @State
  public companyList: any;
  @Action
  public getPrincipalList;
  @Getter
  public isSupperAdmin: boolean;
  @Dependencies(PrincipalService)
  private principalService: PrincipalService;
  @Dependencies(FileUploadService)
  private fileUploadService: FileUploadService;
  private receivAccountRequest: any = [];
  private commissionDetail: any = [];
  //委托方数据实体
  private modifyModel: any = {
    name: "",
    principalCode: "",
    outSourceType: "",
    commonState: "",
    address: "",
    mail: "",
    collectArea: "",
    contents: "",
    contactName: "",
    phone: "",
    areaIds: [],
    companyCode: "",
    id: "",
    startTime: "",
    endTime: "",
    receivAccountsJson: "",
    paymentConfirmType: ""
  };
  //数据校验
  private rules: any = {
    name: [{ required: true, message: "请输入委托方", trigger: "blur" }],
    principalCode: [
      { required: true, message: "请输入委托方代码", trigger: "blur" }
    ],
    outSourceType: [
      { required: true, message: "请选择机构类型", trigger: "change" }
    ],
    commonState: [{ required: true, message: "请选择状态", trigger: "change" }],
    contactName: [{ required: true, message: "请输入联系人", trigger: "blur" }],
    phone: [
      {
        required: true,
        message: "请输入正确的手机号",
        trigger: "blur",
        pattern: /^1(3|4|5|7|8)\d{9}$/
      }
    ],
    paymentConfirmType: [
      { required: true, message: "请选择回款确认方式", trigger: "change" }
    ]
  };

  @Emit("refreshList")
  public refreshList() {}
  @Emit("close")
  public close() {
    this.reset();
  }

  //重置方法
  private reset() {
    const modifyForm: any = this.$refs["modify-form"];
    modifyForm.resetFields();
    this.modifyModel.id = "";
    this.receivAccountRequest = [];
    this.commissionDetail = [];
  }

  /**
   * 反显数据
   */
  private update(data: any) {
    if (!data.id) return;
    this.modifyModel.name = data.name;
    this.modifyModel.address = data.address;
    this.modifyModel.contents = data.contents;
    this.modifyModel.phone = data.phone;
    this.modifyModel.companyCode = data.companyCode;
    this.modifyModel.id = data.id;
    this.modifyModel.principalCode = data.principalCode;
    this.modifyModel.outSourceType = data.outSourceType;
    this.modifyModel.commonState = data.commonState;
    this.modifyModel.mail = data.mail;
    this.modifyModel.areaId = data.areaId;
    this.modifyModel.startTime = this.$filter.dateTimeFormat(data.startTime);
    this.modifyModel.endTime = this.$filter.dateTimeFormat(data.endTime);
    this.modifyModel.collectArea = data.collectArea;
    this.modifyModel.contactName = data.contactName;
    this.modifyModel.paymentConfirmType = data.paymentConfirmType;
    const arr = this.$city.getCityParent(Number(data.areaId));
    this.modifyModel.areaIds = arr ? arr.concat([Number(data.areaId)]) : [];
    this.receivAccountRequest = data.receivAccounts || [];
    this.dataHandler();
    this.commissionDetail = data.commissionDetail;
  }

  /**
   * 收款账户回显数据处理
   */
  private dataHandler() {
    if (this.receivAccountRequest.length) {
      this.receivAccountRequest.map((v, index) => {
        v.fileList = [];
        if (v.qrCodeUrl) {
          // qrCodeUrl即为id
          v.fileList.push({ response: { id: v.qrCodeUrl } });
          // 根基ID查找url
          this.fileUploadService.getUploadFile(v.qrCodeUrl).subscribe(data => {
            v.fileList[0].response.url = data.url;
          });
        }
      });
    }
  }

  /**
   * 新增收款账户
   */
  private onClickAccount() {
    this.receivAccountRequest.push({
      id: "",
      paymentType: "",
      receiveName: "",
      receiveCardNumber: "",
      receiveBank: "",
      fileList: [],
      qrCodeUrl: ""
    });
  }

  /**
   * 新增佣金设置
   */
  private onClickCommision() {
    this.commissionDetail.push({
      overduePeriodStart: "",
      overduePeriodEnd: "",
      paymentAccountType: "",
      rate: "",
      id: ""
    });
  }

  private paramsHandler() {
    const params = {
      ...this.modifyModel,
      receivAccountRequest: this.receivAccountRequest,
      commissionDetail: this.commissionDetail
    };
    params.areaId = this.modifyModel.areaIds[
      this.modifyModel.areaIds.length - 1
    ];
    if (params.receivAccountRequest.length) {
      params.receivAccountRequest.map((v, index) => {
        v.qrCodeUrl =
          v.fileList.length && v.fileList[0].response
            ? v.fileList[0].response.id
            : "";
      });
    }
    params.startTime = this.$filter.dateFormat(this.modifyModel.startTime);
    params.endTime = this.$filter.dateFormat(this.modifyModel.endTime);
    delete params.areaIds;

    return params;
  }

  /**
   * 提交验证并并与数据库交互
   */
  private commit() {
    const modifyForm: any = this.$refs["modify-form"];
    modifyForm.validate(valid => {
      if (!valid) return false;
      const params = this.paramsHandler();
      params.commissionDetail.map(v => {
        if (v.rate > 100) return this.$message.error("佣金比例不能大于100！");
      });
      //根据是否有数据传入决定执行新增还是修改
      this.modifyModel.id ? this.updateClient(params) : this.addClient(params);
    });
  }

  /**
   * 新增委托方信息
   */
  private addClient(params) {
    this.principalService.addPrincipal(params).subscribe(
      data => {
        this.$message.success("新增成功!");
        // 刷新列表
        this.refreshList();
        // 刷新委托方列表
        // this.getPrincipalList();
        // 关闭
        this.close();
      },
      ({ msg }) => {}
    );
  }

  /**
   * 修改委托方信息
   */
  private updateClient(params) {
    this.principalService.updatePrincipal(params).subscribe(
      data => {
        this.$message.success("修改成功!");
        // 刷新列表
        this.refreshList();
        // 更新委托方缓存
        // this.getPrincipalList();
        //关闭
        this.close();
      },
      ({ msg }) => {}
    );
  }
}
</script>

<style lang="less" scoped>
.modify-client-title {
  padding-bottom: 30px;
  padding-left: 30px;
  font-size: 18px;
  font-weight: bold;
}
</style>
